//
//  SEGNaviHeaderScrollviewView.m
//  Commom
//
//  Created by 山刘 on 2018/11/21.
//  Copyright © 2018年 山刘. All rights reserved.
//

#import "SEGNaviHeaderScrollView.h"

#if __has_include(<Commom/YYBaseHeader.h>)
#import <Commom/YYBaseHeader.h>
#else
#import "YYBaseHeader.h"
#endif

#if __has_include(<Commom/SEGModel.h>)
#import <Commom/SEGModel.h>
#else
#import "SEGModel.h"
#endif

#if __has_include(<Commom/SEGColorManager.h>)
#import <Commom/SEGColorManager.h>
#else
#import "SEGColorManager.h"
#endif

#define kSegRandomColor [UIColor colorWithRed:((float)arc4random_uniform(256) /255.0) green:((float)arc4random_uniform(256) /255.0) blue:((float)arc4random_uniform(256) /255.0) alpha:1.0]

static CGFloat margin_item_left_right = 10.0;

@interface SEGNaviHeaderScrollViewContentModel : NSObject
@property (nonatomic, assign) CGFloat oldLength;
@property (nonatomic, assign) CGFloat newLength;
@property (nonatomic, assign) BOOL canOperation;
@property (nonatomic, copy) NSString *content;
@property (nonatomic, assign) CGRect itemFrame;
@property (nonatomic, copy) NSString *url;
@property (nonatomic, assign) BOOL selected;
@end
@implementation SEGNaviHeaderScrollViewContentModel
@end

@interface SEGNaviHeaderScrollViewModel : NSObject
@property (nonatomic, assign) CGFloat maxSingleitemWidth;
@property (nonatomic, assign) CGFloat maxWidth;
@property (nonatomic, assign) CGFloat extraWidth;
@property (nonatomic, strong)NSMutableArray<SEGNaviHeaderScrollViewContentModel*> *data;
@end
@implementation SEGNaviHeaderScrollViewModel
-(NSString *)description{
    return [self yy_modelDescription];
}
@end

@interface SEGNaviHeaderScrollView()
@property (nonatomic, strong) UIScrollView *backgroundView;
@property (nonatomic, strong)SEGNaviHeaderScrollViewModel *localdata;
@end

@implementation SEGNaviHeaderScrollView
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    self.userInteractionEnabled = YES;
    
    self.backgroundColor = [UIColor clearColor];
    [self addSubview:self.backgroundView];
    [self setupUI];
    return self;
}

//界面布局
-(void)setupUI{
    
}

-(void)layoutSubviews{
    [super layoutSubviews];
    self.backgroundView.frame = self.bounds;
    self.backgroundView.contentSize = CGSizeMake(self.backgroundView.width, self.backgroundView.height);
}

/**
 绑定数据源
 
 @param title 标题 格式："aaa,bbb,cccc"
 @param urls 点击标题跳转的url地址 格式："aaa,bbb,cccc"
 @param selected 默认选中的item，从1开始
 */
-(void)restoreItemDataWithTitle:(NSArray*)title urls:(NSArray*)urls selected:(NSInteger)selected{
    self.hidden = NO;
    
    NSArray* titleArr = title;
    NSArray* urlsArr = urls;
    
    __block NSMutableArray<SEGNaviHeaderScrollViewContentModel*> *lengthArrM =[NSMutableArray array];
    __block SEGNaviHeaderScrollViewModel *model = [SEGNaviHeaderScrollViewModel new];
    model.maxSingleitemWidth = self.width/titleArr.count;
    model.maxWidth = self.width;
    
    [titleArr enumerateObjectsUsingBlock:^(NSString*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        CGSize size = [obj boundingRectWithSize:CGSizeMake(HUGE, HUGE) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:16]} context:nil].size;
        size = CGSizeMake(size.width + margin_item_left_right*2, size.height);
        
        SEGNaviHeaderScrollViewContentModel *tmp = [SEGNaviHeaderScrollViewContentModel new];
        tmp.oldLength = size.width;
        tmp.content = obj;
        tmp.url = urlsArr.count > idx ? [urlsArr objectAtIndex:idx] : @"";
        if (idx == selected - 1) tmp.selected = YES;
        
        if (size.width > model.maxSingleitemWidth) {
            tmp.newLength = model.maxSingleitemWidth;
            tmp.canOperation = YES;
        }else{
            tmp.newLength = size.width;
            tmp.canOperation = NO;
            model.extraWidth += model.maxSingleitemWidth - tmp.oldLength;
        }
        [lengthArrM addObject:tmp];
    }];
    
    model.data = lengthArrM;
    CGFloat newLengthToltal = 0;
    if (model.extraWidth > 0.05) newLengthToltal = self.width - [self segRecursiveCalculateWidthWithData:model];
    
    __block CGFloat width = newLengthToltal*0.5;
    
    //计算总体坐标
    [model.data enumerateObjectsUsingBlock:^(SEGNaviHeaderScrollViewContentModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        obj.itemFrame = CGRectMake(width, 0, obj.newLength, self.height);
        width += obj.newLength;
    }];
    self.localdata = model;
    
    for (UIButton *object in self.backgroundView.subviews) if ([object isKindOfClass:[UIButton class]]) [object removeFromSuperview];
    [model.data enumerateObjectsUsingBlock:^(SEGNaviHeaderScrollViewContentModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UIButton * _item = [self segInitScrollViewItem];
        [_item setTitle:obj.content forState:UIControlStateNormal];
        _item.tag = idx;
        [_item setTitleEdgeInsets:UIEdgeInsetsMake(0, margin_item_left_right, 0, margin_item_left_right)];
        [_item sizeToFit];
        _item.frame = obj.itemFrame;
        [_item setSelected:obj.selected];
        //if (obj.selected) [self itemClick:_item];
    }];
}


/**
 动态更新item的位置

 @param urlString item对应的url地址
 */
-(void)resetItemStatusWithUrlString:(NSString*)urlString{
    __block NSInteger index = -1;
    __block BOOL hasUrlString = NO;
    [self.localdata.data enumerateObjectsUsingBlock:^(SEGNaviHeaderScrollViewContentModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj.url isEqualToString:urlString]) {
            index = idx;
            hasUrlString = YES;
        }
        obj.selected = [obj.url isEqualToString:urlString];
    }];

    if (hasUrlString) {
        for (UIButton *object in self.backgroundView.subviews) {
            if ([object isKindOfClass:[UIButton class]]) [object setSelected:(object.tag == index)];
        }
    }
}

/*
 递归平摊宽度
 */
-(CGFloat)segRecursiveCalculateWidthWithData:(SEGNaviHeaderScrollViewModel*)data{
    
    __block NSInteger leftObjectCount = 0;
    [data.data enumerateObjectsUsingBlock:^(SEGNaviHeaderScrollViewContentModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj.canOperation) leftObjectCount += 1;
    }];
    CGFloat maxSingleitemWidth_ = data.extraWidth/leftObjectCount;//平摊的宽度
    
    __block CGFloat extraWidth = 0;
    __block CGFloat newLengthToltal = 0;
    __block BOOL canOperation = NO;
    [data.data enumerateObjectsUsingBlock:^(SEGNaviHeaderScrollViewContentModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj.canOperation) obj.newLength += maxSingleitemWidth_;
        
        if (obj.canOperation && obj.newLength >= obj.oldLength){
            extraWidth += obj.newLength - obj.oldLength;
            obj.newLength = obj.oldLength;
            obj.canOperation = NO;
        }
        
        newLengthToltal += obj.newLength;
        
        if (obj.canOperation) canOperation = YES;
    }];
    
    data.extraWidth = extraWidth;
    if (data.extraWidth > 0.05 && canOperation) {
        newLengthToltal = [self segRecursiveCalculateWidthWithData:data];
    }
    return newLengthToltal;
}


-(UIButton*)segInitScrollViewItem{
    UIButton *_item = [UIButton buttonWithType:UIButtonTypeCustom];
    _item.titleLabel.font = [UIFont systemFontOfSize:16];
    _item.titleLabel.lineBreakMode = NSLineBreakByTruncatingTail;
    [_item setTitleColor:kColor_2 forState:UIControlStateNormal];
    [_item setTitleColor:kColor_1 forState:UIControlStateSelected];
    [_item addTarget:self action:@selector(itemClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.backgroundView addSubview:_item];
    return _item;
}

-(void)itemClick:(UIButton*)sender{
    if (self.localdata.data.count > sender.tag) {
        
        [self.localdata.data enumerateObjectsUsingBlock:^(SEGNaviHeaderScrollViewContentModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            obj.selected = NO;
        }];
        SEGNaviHeaderScrollViewContentModel *response = [self.localdata.data objectAtIndex:sender.tag];
        response.selected = YES;
        
        for (UIButton *object in self.backgroundView.subviews) {
            if ([object isKindOfClass:[UIButton class]]) [object setSelected:NO];
        }
        
        [sender setSelected:YES];
        if (self.delegate && [self.delegate respondsToSelector:@selector(responseWithUrl:)]) {
            [self.delegate responseWithUrl:response.url];
        }
    }
}

#pragma mark - getter
-(UIScrollView *)backgroundView{
    if (!_backgroundView) {
        _backgroundView = [[UIScrollView alloc]init];
        _backgroundView.frame = self.frame;
//        _backgroundView.backgroundColor = self.superview.backgroundColor;
        _backgroundView.contentSize = CGSizeMake(0, 0);
        _backgroundView.showsVerticalScrollIndicator = NO;
        _backgroundView.showsHorizontalScrollIndicator = NO;
    }
    return _backgroundView;
}

-(SEGNaviHeaderScrollViewModel *)localdata{
    if (!_localdata) {
        _localdata = [SEGNaviHeaderScrollViewModel new];
    }
    return _localdata;
}
@end
